const express = require('express')
const app = express()
const path = require('path')

app.use(express.urlencoded())
app.use(express.json())

app.get('/user', (req, res) => {
  const { userId } = req.query
  if (userId !== '001') {
    return res.send({
      code: 10001,
      msg: '获取失败',
      data: null
    })
  }

  res.send({
    code: 10000,
    msg: '获取成功',
    data: {
      name: '程龙',
      age: 20,
      sex: '女'
    }
  })
})

app.get('/userLazy', (req, res) => {
  setTimeout(() => {
    const { userId } = req.query
    if (userId !== '001') {
      return res.send({
        code: 10001,
        msg: '获取失败',
        data: null
      })
    }

    res.send({
      code: 10000,
      msg: '获取成功',
      data: {
        name: '程龙',
        age: 20,
        sex: '女'
      }
    })
  }, 3000)
})

app.post('/adduser', (req, res) => {
  const { name, age, sex } = req.body

  res.send({
    code: 10001,
    msg: '添加成功',
    data: {
      name: '程龙',
      age: 12,
      sex: '男'
    }
  })
})

app.put('/updatauser', (req, res) => {
  const { name, age, sex } = req.body

  res.send({
    code: 10001,
    msg: '更新成功',
    data: {
      name: '程龙',
      age: 12,
      sex: '女'
    }
  })
})

app.delete('/deleteuser', (req, res) => {
  const { userId } = req.query

  if (userId !== '001') {
    return res.send({
      code: 10000,
      msg: '删除失败',
      data: null
    })
  }

  res.send({
    code: 10001,
    msg: '删除成功',
    data: null
  })
})

// 部署静态资源接口
app.get('/1', (req, res) => {
  const filePath = path.resolve(__dirname, './1.axios的基础使用.html')
  res.sendFile(filePath)
})

app.get('/2', (req, res) => {
  const filePath = path.resolve(__dirname, './2.axios请求别名.html')
  res.sendFile(filePath)
})

app.get('/3', (req, res) => {
  const filePath = path.resolve(__dirname, './3.创建axios实例.html')
  res.sendFile(filePath)
})

app.get('/4', (req, res) => {
  const filePath = path.resolve(__dirname, './4.请求拦截器.html')
  res.sendFile(filePath)
})

app.get('/5', (req, res) => {
  const filePath = path.resolve(__dirname, './5.响应拦截器.html')
  res.sendFile(filePath)
})

app.get('/6', (req, res) => {
  const filePath = path.resolve(__dirname, './6.拦截器练习.html')
  res.sendFile(filePath)
})

app.get('/7', (req, res) => {
  const filePath = path.resolve(__dirname, './7.取消请求.html')
  res.sendFile(filePath)
})

app.listen(8080, () => {
  console.log('成功')
})